#include <iostream>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int count = 0;

void* APrint(void* args)
{
    while (true)
    {
        pthread_mutex_lock(&mutex);

        if (count % 2 == 1)
            pthread_cond_wait(&cond, &mutex);

        sleep(1);
        std::cout << "我是线程A" << std::endl;
        count++;

        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
    
}

void* BPrint(void* args)
{
    while (true)
    {
        pthread_mutex_lock(&mutex);

        if (count % 2 == 0)
            pthread_cond_wait(&cond, &mutex);

        sleep(1);
        std::cout << "我是线程B" << std::endl;
        count++;

        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
}

int main()
{
    pthread_t tid1, tid2;

    pthread_create(&tid1, nullptr, APrint, nullptr);
    pthread_create(&tid1, nullptr, BPrint, nullptr);

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);

    return 0;
}